#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <mqueue.h>
#include <signal.h>
#include <string.h>

static const char *queue_name = "";

void signal_handler(int sig)
{
    mq_unlink(queue_name);
    exit(EXIT_SUCCESS);
}

int main(int argc, char const *argv[])
{
    signal(SIGINT, signal_handler);
    signal(SIGTERM, signal_handler);
    char buf[2048];
    if (argc <= 1)
    {
        printf("启动参数不足");
    }

    queue_name = argv[1];

    struct mq_attr attr;
    attr.mq_maxmsg = 10;
    attr.mq_msgsize = 2048;
    sprintf(buf, "/%s", argv[1]);
    mqd_t my_mq = mq_open(buf, O_CREAT | O_RDWR | O_NONBLOCK, 0666, &attr);
    if (my_mq < 0)
    {
        perror("my_mq");
        exit(EXIT_FAILURE);
    }

    // 进程同步
    sleep(5);

    // 开对方的队列
    mqd_t peer_mq;
    if (strcmp(argv[1], "A") == 0)
    {
        strcpy(buf, "/B");
    }
    else if (strcmp(argv[1], "B") == 0)
    {
        strcpy(buf, "/A");
    }
    else
    {
        mq_unlink(buf);
        exit(EXIT_FAILURE);
    }

    peer_mq = mq_open(buf, O_RDWR | O_NONBLOCK);
    if (peer_mq < 0)
    {
        perror(buf);
        exit(EXIT_FAILURE);
    }

    while (1)
    {
        // 查看自己的队列，看看是否有消息
        int result = mq_receive(my_mq, buf, 2048, 0);
        if (result > 0)
        {
            printf("%s", buf);
            printf("\n");
        }

        scanf("%s", buf);
        result = mq_send(peer_mq, buf, 2048, 0);
        if (result < 0)
        {
            perror("mq_send");
            exit(EXIT_FAILURE);
        }
    }

    return 0;
}
